<template>
    <div class="myContainer">
        <!-- 头部标题 start -->
        <el-row>
            <el-col :span="24">
                <div class="myHeadeTitle">部门管理</div>
            </el-col>
        </el-row>
        <!-- 头部标题 end -->
        <!-- 页面主体 start -->
        <el-row>
            <!-- 主体左侧列表树 start -->
            <el-col :span="6">
                <el-container class="myLeftContainer zcgl">
                    <el-menu
                        v-loading="menuLoading"
                        :default-active="deptIdSelected"
                        @open="handleOpen"
                        @close="handleClose"
                        @select="handleSelect"
                        :default-openeds="defaultOpen">
                        <!--  -->
                        <dept-sub-menu v-if='deptTree&&deptTree.length>0' :subMenu='deptTree'></dept-sub-menu>
                    </el-menu>
                </el-container>
            </el-col>
            <!-- 主体左侧列表树 end -->
            <!-- 主体右侧功能展示 start -->
            <el-col :span="18">
                <div class="myBtnDiv">
                    <el-button type="primary" v-if="isShow(102)" @click="openAddDept"><i class="el-icon-circle-plus-outline"></i>添加下级部门</el-button>
                    <el-button class="myBgGreen" v-if="isShow(103)" @click="openModifyDept"><i class="el-icon-edit-outline"></i>修改部门</el-button>
                    <el-button type="danger" v-if="isShow(104)" @click="onDelete"><i class="el-icon-remove-outline"></i>删除部门</el-button>
                </div>
                <template>
                    <el-tabs type="border-card"
                             v-model="tabSelected"
                             @tab-click="handleTabClick"
                    >
                        <el-tab-pane label="人员信息" name="staffInfo">
                            <div class="myHeadeTitle">
                                <div class="myTitle">人员信息</div>
                                <div class="mySearchDiv">
                                    <el-form :inline="true" >
                                        <el-form-item>

                                            <el-input v-model="searchStaffKW" class="mySearchText" placeholder="输入关键字进行搜索"></el-input>
                                        </el-form-item>
                                        <el-form-item>

                                            <el-button class="myBgGreen" @click="handleStaffSearch">搜索</el-button>
                                        </el-form-item>
                                    </el-form>
                                </div>
                            </div>
                            <template>
                                <el-table
                                    stripe
                                    v-loading="staffLoading"
                                    :data="staffList"
                                    border
                                    style="width: 100%">
                                    <el-table-column
                                        type="index"
                                        label="序号"
                                        width="100">
                                    </el-table-column>
                                    <el-table-column

                                        prop="user_name"
                                        label="员工姓名">
                                    </el-table-column>
                                    <el-table-column

                                        prop="phone"
                                        label="员工电话">
                                    </el-table-column>
                                    <el-table-column

                                        prop="role_name"
                                        label="职务">
                                    </el-table-column>
                                    <el-table-column
                                        width="100"
                                        label="操作">
                                        <template scope="scope">
                                            <el-button class="look" type="text" size="small" v-if="isShow(107)" @click="onUnbundDept(scope.row.staff_id)">解除关联</el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </template>
                            <div class="block">
                                <el-pagination

                                    @size-change="handleStaffSizeChange"
                                    @current-change="handleStaffCurrentChange"
                                    :current-page="staffPageNum"
                                    :page-size="staffPageSize"
                                    layout="total, sizes, prev, pager, next, jumper"

                                    :total="staffTotal">
                                </el-pagination>
                            </div>
                        </el-tab-pane>

                        <el-tab-pane label="角色/职务信息" name="roleInfo">
                            <div class="myHeadeTitle">
                                <div class="myTitle">角色/职务信息</div>
                                <div class="mySearchDiv">
                                    <el-button class="myBgGreen" v-if="isShow(106)" @click="openRole">添加角色/职务</el-button>
                                </div>
                            </div>
                            <template>
                                <el-table
                                    stripe
                                    v-loading="roleLoading"
                                    :data="roleList"
                                    border
                                    style="width: 100%">
                                    <el-table-column
                                        type="index"
                                        label="序号"
                                        width="100">
                                    </el-table-column>
                                    <el-table-column
                                        prop="role_name"
                                        label="角色名称">
                                    </el-table-column>
                                    <el-table-column
                                        width="150"
                                        prop="data_rule"
                                        label="角色数据权限">
                                        <template scope="scope">
                                            <span>{{scope.row.data_rule | dataRule}}</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        width="100"
                                        label="操作">
                                        <template scope="scope">
                                            <el-button class="look" type="text" size="small" v-if="isShow(108)" @click="onUnbundRole(scope.row.role_id)">解除关联</el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </template>

                        </el-tab-pane>

                        <el-tab-pane label="片区/小区" name="areaInfo">
                            <div class="myHeadeTitle">
                                <div class="myTitle">片区/小区信息</div>
                                <div class="mySearchDiv">
                                    <el-button class="myBgGreen" v-if="isShow(105)" @click="openDateTree">添加片区/小区</el-button>
                                </div>
                            </div>
                            <template>
                                <el-table
                                    stripe
                                    v-loading="dataLoading"
                                    :data="dataList"
                                    border
                                    style="width: 100%">
                                    <el-table-column
                                        type="index"
                                        label="序号"
                                        width="100">
                                    </el-table-column>
                                    <el-table-column
                                        prop="label"
                                        label="名称">
                                    </el-table-column>
                                    <el-table-column
                                        width="100"
                                        label="操作">
                                        <template scope="scope">
                                            <el-button class="look" type="text" size="small" v-if="isShow(109)" @click="onUnbundDataTree">解除关联</el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </template>

                        </el-tab-pane>
                    </el-tabs>
                </template>
            </el-col>
            <!-- 主体右侧功能展示 end -->
        </el-row>
        <!-- 页面主体 end -->


        <!--添加部门弹出框 start-->

        <el-dialog
            v-loading = 'dlgDeptLoading'
            :title="dlgDeptTitle"
            :visible.sync="newDeptDialogVisible">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
                <el-row>
                    <el-col :span="3" class="myLeftMsg">
                        <span class="require myVA_M">*</span> 部门名称 :
                    </el-col>
                    <el-col :span="20">
                        <el-form-item prop="deptName">
                            <el-input auto-complete="off" placeholder="请输入部门名称" v-model="ruleForm.deptName"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- <el-form-item label="部门名称:" prop="deptName">
                  <el-input auto-complete="off" placeholder="请输入部门名称" v-model="ruleForm.deptName"></el-input>
                </el-form-item> -->
                <!-- <div slot="footer" class="dialog-footer"> -->
                <el-row class="mymarginTop_10px myTextRight">
                    <el-button type="primary" class="myBgGreen" @click="handleDlgDeptClicke('ruleForm')">确 定</el-button>
                    <el-button @click="newDeptDialogVisible = false">取 消</el-button>
                </el-row>
                <!-- </div> -->
            </el-form>
        </el-dialog>
        <!--添加部门弹出框 end-->
        <!--添加角色职务弹出框 start-->

        <el-dialog title="添加角色/职务" class="myRoleDialog" :visible.sync="newRoleDialogVisible">
            <div>
                <el-input placeholder="输入关键字进行搜索" v-model="kw" class="input-with-select">
                    <el-button type="primary" slot="append" class="el-icon-search"></el-button>
                </el-input>
            </div>
            <div class="mymarginTop_10px myOV_y_400px">
                <el-tree
                    ref="roleData"
                    v-loading="roleDataListLoading"
                    :data="roleDataList"
                    node-key="role_id"
                    :props="RoleDataProps"
                    :filter-node-method="filterNode"
                    show-checkbox>
                </el-tree>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" class="myBgGreen" @click="handleRoleClick">提 交</el-button>
                <el-button @click="newRoleDialogVisible = false">取 消</el-button>
            </div>
        </el-dialog>
        <!--添加角色职务弹出框 end-->
        <!--添加集团/片区/小区弹出框 start-->
        <el-dialog title="片区/小区" class="myRoleDialog" :visible.sync="newAreaDialogVisible">
            <el-menu
                v-loading="dataTreeLoading"
                :default-active="dataTreeSelected"
                @open="handleDataTreeSelect"
                @close="handleDataTreeSelect"
                @select="handleDataTreeSelect"
                class="mymarginTop_10px myOV_y_400px"
            ><!-- :default-openeds="['1','1-1']"-->
                <dept-sub-menu v-if='dataTreeList&&dataTreeList.length>0' :subMenu='dataTreeList'></dept-sub-menu>
            </el-menu>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" class="myBgGreen" @click="handleDateTreeClick">提 交</el-button>
                <el-button @click="newAreaDialogVisible = false">取 消</el-button>
            </div>
        </el-dialog>
        <!--添加集团/片区/小区弹出框 end-->
        <!-- 删除部门 start -->
        <el-dialog title="删除部门" class="myRoleDialog" :visible.sync="deleteDeptDig">
            确定要删除 【{{deptNameText}}】？
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" class="myBgGreen" @click="isDeleteDept">确 定</el-button>
                <el-button @click="deleteDeptDig = false">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 删除部门 end -->
    </div>
</template>

<style>
    .el-button--warning span{
        color: #fff;
    }
    .el-button--danger span{
        color: #fff;
    }
    .el-icon-caret-bottom{
        transform: rotate(-90deg);
        transition: transform .3s;
    }
    .el-submenu.is-opened > .el-submenu__title .el-icon-caret-bottom{
        transform: rotate(0deg);
    }
</style>
<style scoped>
    i {
        color: white;
    }
    .myContainer{
        background: #fff;
        padding: 10px;
    }
    .myHeadeTitle{
        color: #000;
        font-weight: 500;
        font-size: 16px;
        padding-bottom: 10px;
        border-bottom: 1px solid #dbdbdb;
        margin-bottom:10px;
    }
    .myHeadeTitle:before,.myHeadeTitle:after{
        content: " ";
        display: block;
        clear: both;
    }
    .myLeftContainer{
        height: 800px;
        overflow-y:scroll;
        width: 95%;
    }
    .myLeftContainer::-webkit-scrollbar{
        width: 0px;
        height: 0px;
    }
    .myLeftContainer .el-menu{
        width: 100%;
    }
    .myBgGreen{
        background: #00c2a9;
        border-color: #00c2a9;
        color: #fff;
    }
    .myBgGreen:hover{
        background: #33ceba;
    }
    .myBtnDiv{
        padding-bottom: 10px;
    }
    .mySearchDiv{
        float: right;
    }
    .myTitle{
        line-height: 40px;
        float:left;
    }
    .mySearchText{
        min-width: 200px;
    }
    .el-form-item{
        margin-bottom: 0 !important;
    }
    .myInput{
        width: 200px;
        height: 36px;
        border: 1px solid #ddd;
        background: #000 !important
    }
    .myDialogSearchText{
        width: 360px;
    }
    .mymarginTop_10px{
        margin-top: 10px;
    }
    .myOV_y_400px{
        max-height: 400px;
        min-height: 200px;
        overflow-y:scroll;
        border: 1px solid #d1dbe5;
    }
    .myTextRight{
        text-align: right;
    }
    .myLeftMsg{
        line-height: 40px;
        text-align: right;
        padding-right: 10px;
    }
    .myVA_M{
        vertical-align: middle;
    }
</style>

<script>
    import DeptSubMenu from '@/components/DeptSubMenu';
    import { getDeptInfo, getDeptStaffInfo, getDeptRoleInfo,
        getDeptDataTree, addDept, modifyDept, bindDataTree,
        setDeptRoleInfo , deleteDept , unbundDept ,
        unbundRole , unbundDataTree } from '@/api/dept';
    import { getDataTree } from '@/api/area';
    import { getRoleList } from '@/api/role';
    export default {
        data(){
            return{
                // 部门树
                deptTree: [],
                deptIdSelected: "0",
                defaultOpen:['0-新鸥鹏物业集团'],
                menuLoading: false,
                deptName: "",

                // tab信息
                tabSelected: "staffInfo",

                // 员工信息
                staffList: null,
                searchStaffKW: "",
                staffPageNum: 1,
                staffPageSize: 10,
                staffTotal: null,
                staffLoading: false,

                // 角色信息
                roleList: null,
                roleLoading: false,

                // 集团/片区/小区信息
                dataList: null,
                dataLoading: false,

                // 对话框loading
                dlgDeptLoading: false,
                dlgDeptTitle: '添加部门',

                newDeptDialogVisible:false,
                newRoleDialogVisible:false,
                newAreaDialogVisible:false,

                // 绑定片区、小区
                dataTreeLoading: false,
                dataTreeSelected: null,
                dataTreeList:[],

                // 绑定角色
                roleDataListLoading: false,
                roleDataList:[],
                RoleDataProps: {
                    label: 'role_name'
                },

                ruleForm:{},
                rules:{
                    deptName:[
                        { required: true, message: '请输入部门名称', trigger: 'blur' }
                    ]
                },
                deleteDeptDig:false,
                deptNameText:'',

                kw:''
            }
        },
        components: {
            DeptSubMenu
        },
        created(){
            document.title="部门管理";
            this.getDeptTree(this);
            this.getDeptStaff();
        },
        filters: {
            dataRule: function(value) {
                if (value === 'all') {
                    return '可见全部';
                } else if (value === 'own') {
                    return '可见个人';
                }
            }
        },
        watch: {
            kw(val) {
                this.$refs.roleData.filter(val);
            }
        },
        methods:{
            filterNode(value, data) {
                if (!value) return true;
                return data.role_name.indexOf(value) !== -1;
            },
            handleRoleClick() {
                this.setDeptRoleInfo();
            },
            setDeptRoleInfo() {
                console.log(this.$refs.roleData.getCheckedNodes());
                let checkNode = this.$refs.roleData.getCheckedNodes();
                if (!checkNode.length > 0) {
                    return;
                }

                let nodes = new Array(checkNode.length);
                for (let i = 0; i < checkNode.length; i++) {
                    nodes[i] = checkNode[i].role_id;
                }

                let vm = this;
                vm.roleDataListLoading = true;
                setDeptRoleInfo(this.deptIdSelected, nodes)
                    .then(response => {
                        vm.roleDataListLoading = false;
                        vm.newRoleDialogVisible = false;
                        vm.getDeptRole();
                    })
                    .catch(error => {
                        vm.roleDataListLoading = false;
                        vm.newRoleDialogVisible = false;
                    })
            },
            getRoleList() {
                let vm = this;
                let params = {
                    page_num: 1,
                    page_size: 1000
                };

                vm.roleDataListLoading = true;
                getRoleList(params)
                    .then( response => {
                        let res = response.data;
                        vm.roleDataList = res.rows;

                        vm.roleDataListLoading = false;
                    })
                    .catch( error => {
                        vm.roleDataListLoading = false;
                    })
            },
            openRole() {
                this.roleDataList = [];
                this.newRoleDialogVisible = true;
                this.kw='';
                this.getRoleList();
            },

            handleDateTreeClick() {
                let vm = this;
                bindDataTree(vm.deptIdSelected, vm.dataTreeSelected)
                    .then(response => {
                        vm.newAreaDialogVisible = false;
                        if (vm.tabSelected === 'areaInfo') {
                            vm.getDeptData();
                        }
                    })
                    .catch(response => {
                        vm.newAreaDialogVisible = false;
                    })
            },
            openDateTree() {
                this.dataTreeList = [];
                this.newAreaDialogVisible = true;
                this.getDataTree();
            },
            getDataTree() {
                let vm = this;
                vm.dataTreeLoading = true;
                getDataTree()
                    .then(response => {
                        let res = response.data;
                        vm.dataTreeList = res;
                        vm.dataTreeLoading = false;
                    })
                    .catch(error => {

                        vm.dataTreeLoading = false;
                    })
            },
            handleDataTreeSelect(key, keyPath) {
                let str = key.split('-')
                this.dataTreeSelected = str[0];
            },
            openAddDept() {
                this.newDeptDialogVisible = true;
                this.dlgDeptTitle = '添加部门';
            },
            openModifyDept() {
                this.newDeptDialogVisible = true;
                this.dlgDeptTitle = '修改部门';
            },
            handleDlgDeptClicke(formName) {
                if (this.dlgDeptTitle === '添加部门') {
                    this.$refs[formName].validate((valid) => {
                        if (valid) {
                            this.addDept();
                            this.$message.success("执行成功！");
                        } else {
                            this.$message.error("执行失败！");
                            return false;
                        }
                    });
                } else {
                    this.$refs[formName].validate((valid) => {
                        if (valid) {
                            this.modifyDept();
                            this.$message.success("执行成功！");
                        } else {
                            this.$message.error("执行失败！");
                            return false;
                        }
                    });
                }
            },
            addDept() {
                let vm = this;
                let data = {
                    dept_name: vm.ruleForm.deptName,
                    pid: vm.deptIdSelected
                };

                vm.dlgDeptLoading = true;
                addDept(data)
                    .then(response => {
                        vm.newDeptDialogVisible = false;
                        vm.dlgDeptLoading = false;
                        this.ruleForm.deptName="";
                        vm.getDeptTree(vm);
                    })
                    .catch(error => {

                        vm.newDeptDialogVisible = false;
                        vm.dlgDeptLoading = false;
                    })

            },

            modifyDept() {
                let vm = this;
                let data = {
                    dept_name: vm.ruleForm.deptName,
                };

                vm.dlgDeptLoading = true;
                modifyDept(vm.deptIdSelected, data)
                    .then(response => {
                        vm.newDeptDialogVisible = false;
                        vm.dlgDeptLoading = false;
                        this.ruleForm.deptName="";
                        vm.getDeptTree(vm);
                    })
                    .catch(error => {

                        vm.newDeptDialogVisible = false;
                        vm.dlgDeptLoading = false;
                    })
            },

            getDeptTree(vm) {
                vm.menuLoading = true;
                getDeptInfo(0)
                    .then(response => {
                        let res = response.data;
                        vm.deptTree = res;
                        vm.menuLoading = false;
                    })
                    .catch(error => {
                        vm.menuLoading = false;

                    });
            },
            getDeptStaff() {
                let vm = this;
                let params = {
                    kw: this.searchStaffKW,
                    page_num: this.staffPageNum,
                    page_size: this.staffPageSize
                };
                vm.staffLoading = true;
                vm.staffList = [];
                getDeptStaffInfo(this.deptIdSelected, params)
                    .then(response => {
                        let res = response.data;
                        vm.staffList = res.rows;
                        vm.staffTotal = res.total;
                        vm.staffPageNum = res.page_num;
                        vm.staffPageSize = res.page_size;

                        vm.staffLoading = false;
                    })
                    .catch(error => {
                        vm.staffLoading = false;
                    });
            },
            getDeptRole() {
                let vm=this;
                vm.roleLoading = true;
                vm.roleList = [];
                getDeptRoleInfo(this.deptIdSelected)
                    .then(response => {
                        let res = response.data;
                        vm.roleList = res;

                        vm.roleLoading = false;
                    })
                    .catch(error => {
                        vm.roleLoading = true;
                    });
            },
            getDeptData() {
                let vm=this;
                vm.dataLoading = true;
                vm.dataList = [];
                getDeptDataTree(this.deptIdSelected)
                    .then(response => {
                        let res = response.data;
                        vm.dataList = res;

                        vm.dataLoading = false;
                    })
                    .catch(error => {
                        vm.dataLoading = false;
                    });
            },

            handleSelect(key, keyPath) {
                let str = key.split('-');
                this.defaultOpen=keyPath;
                this.deptIdSelected = str[0];
                this.deptNameText= str[1];
                this.handleTabClick();
            },
            handleOpen(key, keyPath) {
                let str = key.split('-');
                this.deptIdSelected = str[0];
                this.deptNameText= str[1];
                this.handleTabClick();
            },
            handleClose(key, keyPath) {
                let str = key.split('-');
                this.deptIdSelected = str[0];
                this.deptNameText= str[1];
                this.handleTabClick();
            },

            handleStaffSizeChange(val) {
                this.staffPageSize = val;
                this.getDeptStaff();
            },

            handleStaffCurrentChange(val) {
                this.staffPageNum = val;
                this.getDeptStaff();
            },
            handleStaffSearch() {
                this.getDeptStaff();
            },
            handleTabClick() {
                if (this.tabSelected === 'staffInfo') {
                    this.getDeptStaff();
                    // console.log('staffInfo');
                } else if (this.tabSelected === 'roleInfo') {
                    this.getDeptRole();
                    // console.log('roleInfo');
                } else if (this.tabSelected === 'areaInfo') {
                    this.getDeptData();
                    // console.log('areaInfo');
                }
            },
            onDelete(){//删除部门
                this.deptNameText!=''?this.deleteDeptDig=true:this.$message.info("请先选择要操作的部门！");
            },
            isDeleteDept(){//删除部门
                deleteDept(this.deptIdSelected).then(response => {
                    let res=response.data;
                    this.getDeptTree(this);
                    this.$message.success("执行成功！");
                    this.deptNameText='';
                    this.deleteDeptDig=false;
                }).catch(error=> {
                    this.$message.error("执行失败！"+error.response.data.error_msg);
                    this.deleteDeptDig=false;
                })
            },
            onUnbundDept(staff_id){//解除单员工部门关系
                let vm=this;
                vm.$confirm('您确定要解除绑定吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    unbundDept(staff_id).then(response => {
                        let res=response.data;
                        vm.getDeptStaff();
                        vm.$message.success("执行成功！");
                    }).catch(error => {
                        vm.$message.error("执行失败！"+error.response.data.error_msg);
                    })
                }).catch(() => {
                    vm.$message({
                        type: 'info',
                        message: '已取消执行'
                    });
                });
            },
            onUnbundRole(role_id){//解除部门员工关系
                let vm=this;
                vm.$confirm('您确定要解除绑定吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    unbundRole(vm.deptIdSelected,role_id).then(response => {
                        let res=response.data;
                        vm.getDeptRole();
                        vm.$message.success("执行成功！");
                    }).catch(error => {
                        vm.$message.error("执行失败！"+error.response.data.error_msg);
                    })
                }).catch(() => {
                    vm.$message({
                        type: 'info',
                        message: '已取消执行'
                    });
                });
            },
            onUnbundDataTree(){//删除关联部门和数据树
                let vm=this;
                vm.$confirm('您确定要解除绑定吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    unbundDataTree(vm.deptIdSelected).then(response => {
                        let res=response.data;
                        vm.getDeptData();
                        vm.$message.success("执行成功！");
                    }).catch(error => {
                        vm.$message.error("执行失败！"+error.response.data.error_msg);
                    })
                }).catch(() => {
                    vm.$message({
                        type: 'info',
                        message: '已取消执行'
                    });
                });
            }
        }
    }
</script>

